const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { BadRequest } = require('http-errors')
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');
const moment = require('moment');
const {config, client, singleFileUpload} = require('../../utils/aliyun');
moment.locale('zh-cn');


// 连接 MongoDB 数据库，替换为你自己的真实连接字符串
mongoose.connect('mongodb://localhost:27017/control-book', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});


const Book = require('../../models/book'); // 假设你有对应的 Mongoose 模型定义文件
const Category = require('../../models/category');
// const User = require('../../models/userModel');
// const userAuth = require('../../middlewares/user-auth');

// 获取所有书籍
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage) || 1);
    const pageSize = Math.abs(Number(query.pageSize) || 10);
    const skip = (currentPage - 1) * pageSize;

    const condition = {};

    if (query.categoryId) {
      condition.categoryId = query.categoryId;
    }
    if (query.borrowName) {
      condition.borrowName = query.borrowName;
    }
    if (query.userId) {
      condition.userId = query.userId;
    }
    if (query.name) {
      condition.name = { $regex: new RegExp(query.name, 'i') };
    }
    if (query.author) {
      condition.author = { $regex: new RegExp(query.author, 'i') };
    }
    if (query.content) {
      condition.content = { $regex: new RegExp(query.content, 'i') };
    }
    if (query.borrowBook === 'true') {
      condition.borrowBook = true;
    } else if (query.borrowBook === 'false') {
      condition.borrowBook = false;
    }

    const totalCount = await Book.countDocuments(condition);
    const books = await Book.find(condition)
      .populate('categoryId')
      // .populate('categoryId', 'id name')
     .skip(skip)
     .limit(pageSize)
     .sort({ _id: -1 });


     
    success(res, '图书查询成功', {
      books,
      pagination: {
        total: totalCount,
        currentPage,
        pageSize
      }
    });
  } catch (error) {
    console.log(error)
    failure(res, error);
  }
});

// 获取单个书籍
// 获取单个书籍详细信息
router.get('/:_id', async function (req, res) {
  try {
    const book = await Book.findById(req.params._id)
    //  .populate('categoryId', 'id name')
    //  .populate('userId', 'id username');
    if (!book) {
      throw new NotFoundError(`ID: ${req.params._id}的文章未找到`);
    }
    success(res, '图书查询成功', { book });
  } catch (error) {
    failure(res, error);
  }
});


// 创建书籍
router.post('/', async function (req, res) {
  try {
    const body = filterBook(req);
    const categoryId = await Category.findOne({rank: body.rank})
    const book = new Book(body);
    book.categoryId = categoryId._id;
    await book.save();
    success(res, '图书创建成功', { book }, 201);
  } catch (error) {
    console.log('~~~~')
    console.log(error);
    failure(res, error);
  }
});

// 更新书籍
// 更新图书
router.put('/:_id', async (req, res) => {
  try {
      const book = await Book.findById(req.params._id);
      if (!book) {
          throw new NotFoundError(`ID: ${req.params._id}的文章未找到`);
      }

      const body = filterBook(req);
      console.log(body)
      await Book.updateOne({_id: req.params._id}, { $set: body });
      // await book.save();
      success(res, '图书更新成功', { book });
  } catch (error) {
      console.log(error);
      failure(res, error);
  }
});


// 删除图书
router.delete('/:_id', async function (req, res) {
  try {
    const book = await Book.findById(req.params._id);
    if (!book) {
      throw new NotFoundError(`ID: ${req.params._id}的文章未找到`);
    }
    await book.deleteOne();
    success(res, '图书删除成功');
  } catch (error) {
    console.log(error)
    failure(res, error);
  }
});

router.post('/upload', function (req, res) {
  try {
    singleFileUpload(req, res, function (error) {
      if (error) {
        return failure(res, error);
      }

      if (!req.file) {
        console.log(req.file)
        return failure(res, new BadRequest('请选择要上传的文件。'));
      }
      const url = req.file.url;
      success(res, '上传成功。', { picture: req.file });
    });
  } catch (error) {
    console.log(error)
    failure(res, error);
  }
})


// 过滤书籍请求数据的函数，提取需要的字段构建创建或更新书籍的数据对象
function filterBook(req) {
  return {
    name: req.body.name,
    author: req.body.author,
    content: req.body.content,
    categoryId: req.body.categoryId,
    userId: req.body.userId,
    picture: req.body.picture,
    likesCount: req.body.likesCount,
    borrowName: req.body.borrowName,
    createdAt: new Date(),
    updatedAt: new Date(),
    rank: req.body.rank,
  };
}
module.exports = router;
